import { System, World } from '@ecs/index'
import { Position, Size, Velocity } from '../components'

/**
 * 速度系统
 * @description 计算物体的x、y轴运动速度
 */
export class VelocitySystem extends System {
  constructor(private readonly canvas: HTMLCanvasElement) {
    super()
  }

  public update(world: World): void {
    for (const [entity, componentMap] of world.view(Position, Size, Velocity)) {
      const position = componentMap.get(Position)
      const size = componentMap.get(Size)
      const velocity = componentMap.get(Velocity)

      velocity.vy += velocity.g
      position.x += velocity.vx
      position.y += velocity.vy

      if (entity.name === 'floor') {
        // 地板循环向左移动：只要 x坐标 < 视口宽度 - 地板图宽度 则 地板图会和背景出现间隙 因此重置为0
        if (position.x < this.canvas.width - size.w) {
          position.x = 0
        }
      }
    }
  }

  public destory(): void {}
}
